import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from "./store";
import ElementPlus, { ElMessage } from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from 'axios'

import NProgress from 'nprogress'   // 导入 nprogress

import 'nprogress/nprogress.css' // 导入样式，否则看不到效果


axios.interceptors.request.use((config) => {

  if (config.url != '/api/login/login_user') {
    config.headers.token = localStorage.getItem('token')
    if (localStorage.getItem('token') == null) {
      ElMessage({
        message: '请先登录',
        type: 'error'
      })
      router.push('/')
    } else {
      return config;
    }
  }

  return config;

})

axios.interceptors.response.use((res) => {
  if (res.data.code === 401) {
    ElMessage({
      message: res.data.message + '为您跳转到登录页',
      type: 'error'
    })
    localStorage.clear();
    router.push('/')
  }
  return res;
}, (error) => {
  return Promise.reject(error);
});




router.beforeEach((to, from, next) => {
  NProgress.start()
  next()
})

router.afterEach(() => {
  NProgress.done()
})


const app = createApp(App)
app.use(store)
app.use(router)
app.use(ElementPlus)
app.mount('#app')

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}